/**
 * Copyright 2022 meituan.com Inc. All Rights Reserved.
 */
package org.example.server.controller;

import org.example.api.Dog;
import org.example.server.context.DogContext;
import org.example.server.context.UrlClassLoaderContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @author zhangxiaofan08
 * @version 1.0 2022/3/1
 */
@RestController
public class TestJarController {
    @GetMapping("/loadJar")
    public String loadJar(@RequestParam String key, @RequestParam String className) {
        String jarFilePath = System.getProperty("user.home") + "/Workspaces/IdeaProjects/TestLoadJar/server/src/main/resources/jar-1.0-SNAPSHOT.jar";
        File jarFile = new File(jarFilePath);
        ClassLoader parentClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()}, parentClassLoader);
            Thread.currentThread().setContextClassLoader(urlClassLoader);
            Class<?> targetClass = urlClassLoader.loadClass(className);
            Dog dog = (Dog) targetClass.newInstance();
            DogContext.set(key, dog);
            UrlClassLoaderContext.set(key, urlClassLoader);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Thread.currentThread().setContextClassLoader(parentClassLoader);
        }
        return "ok";
    }

    @GetMapping("/exe")
    public String exe(@RequestParam String key) {
        Dog dog = DogContext.get(key);
        return dog.getName();
    }

    @GetMapping("/unload")
    public String unload(@RequestParam String key) {
        DogContext.remove(key);
        UrlClassLoaderContext.unload(key);
        return "ok";
    }

}
